<?php
namespace Frieza\Modules\Topic\Controllers;

use App\Exceptions\InputErrorException;
use Illuminate\Support\MessageBag;
use App\Http\Controllers\Controller;
use App\Pockets\GridDataModel as pGridDataModel;
use App\Admin\Extensions\Tools\UserButton;
use Encore\Admin\Facades\Admin;
use Encore\Admin\Grid;
use Encore\Admin\Layout\Content;
use Encore\Admin\Widgets\Form;
use Encore\Admin\Widgets\Tab;
use Illuminate\Http\Request;
use Doraemon\model\TopicTab;
use Doraemon\tools\ImgUrl;
use Doraemon\service\position\UserProfileModule;
use Doraemon\service\position\AdmOperationModule;
use Doraemon\model\Position\PositionRules;
use Doraemon\service\TopicActivityAnswer;
use Doraemon\service\Photos;


class TopicTabController extends Controller
{
    const PAGE_SIZE = 20;

    const SHOW_TYPE_TIME = 1;
    const SHOW_TYPE_NONE = 2;
    const SHOW_TYPE = [
        self::SHOW_TYPE_TIME => '时间段展示',
        self::SHOW_TYPE_NONE => '隐藏'
    ];

    public function __construct()
    {
        parent::__construct();
        Admin::script('$(".pjax-container").attr("id","pjax-container");');
    }

    private function _filterWhere($params){
        if(isset($params['_columns_'])){
            unset($params['_columns_']);
        }
        if(isset($params['_pjax'])){
            unset($params['_pjax']);
        }
        $page = isset($params['page']) ? $params['page'] : 1;
        $pageSize = isset($params['per_page']) ? $params['per_page'] : self::PAGE_SIZE;
        $limit = [($page - 1) * $pageSize, $pageSize];
        unset($params['page']);
        $where = [];
        foreach ($params as $_k => &$_v) {
            if ($_v <> '') {
                $where[$_k] = $_v;
            }
        }
        $data = [
            'LIMIT' => $limit,
        ];

        if (!empty($where)) {
            $data['AND'] = $where;
        }

        return $data;
    }

    public function index(Request $request, Content $content, $id)
    {
        $request = $request->all();

        $request = self::_filterWhere($request);
        return $content
            ->header('Tab管理')
            ->breadcrumb(
                ['text' => '话题管理', 'url' => '/topic/index'],
                ['text' => '话题tab管理', 'url' => '/topic/topictab/'.$id]
            )
            ->row('话题id为：'.$id)
            ->body(self::listAction($request, $id));
    }

    public function listAction($request, $id)
    {
        $tab_list = TopicTab::getTabListsByTopicId($id);
        $tab_ids = array_column($tab_list, 'id');
        $taskRules = AdmOperationModule::getPositionRulesById($tab_ids, PositionRules::MODULE_TYPE_TOPIC_TAB);
        foreach ($tab_list as &$row) {
            $row['user_profile'] = $taskRules[$row['id']] ?? [];
            if($row['start_time'] == '0000-00-00 00:00:00' && $row['end_time'] == '0000-00-00 00:00:00') {
                $row['show_type'] = self::SHOW_TYPE_NONE;
            } else {
                $row['show_type'] = self::SHOW_TYPE_TIME;
            }
        }
        $gridModel = new pGridDataModel($tab_list, count($tab_list), [
            'perPage' => $request['per_page'] ? : $request['LIMIT'][1]
        ]);

        $listGrid = Admin::grid($gridModel, function (Grid $grid) {
            $grid->disableFilter();
            $grid->disableExport();
            $grid->disableRowSelector();
            $grid->disablePagination();

            $grid->column('id', 'tab_id')->width(100)->sort();
            $grid->column('topic_id', '话题id')->width(100);
            $grid->column('title', '标题')->display(function() {
                return "<a href='list/".$this->topic_id.'/'.$this->id."'>$this->title</a>";
            })->width(150);
            $grid->column('pic_id', '气泡信息')->display(function() {
                if(empty($this->pic_id)) {
                    return '-';
                }
                return "<img src=".ImgUrl::getUrl(ImgUrl::APPTYPE_OP, $this->pic_id, ImgUrl::IMAGE_SIZE_ORI_NPHONE)." width='200' /><br/>"."气泡始时间：".$this->pic_start_time."<br/>"."气泡结束时间".$this->pic_end_time;
            });
            $grid->column('show_type', 'tab展示状态')->replace(self::SHOW_TYPE);
            $grid->column('start_time', 'tab起止时间')->display(function() {
                if($this->show_type == self::SHOW_TYPE_NONE) {
                    return '-';
                }
                return '开始时间：'. $this->start_time."<br/>".'结束时间：'. $this->end_time;
            });
            $grid->column('addtime', '添加时间')->display(function() {
                return $this->addtime;
            });
            $grid->column('user_profile', '分群信息')->userProfile();

        });

        $list = $listGrid->render();

        return $list;
    }

    public function tabAnswerList(Request $request, Content $content, $id, $tab_id)
    {
        $request = $request->all();
        $request = self::_filterWhere($request);
        return $content
            ->header('tab中回答列表')
            ->breadcrumb(
                ['text' => '话题管理', 'url' => '/topic/index'],
                ['text' => '话题tab管理', 'url' => '/topic/topictab/'.$id],
                ['text' => 'tab回答列表', 'url' => '/topic/topictab/list/'.$id.'/'.$tab_id]
            )
            ->row('话题id为：'.$id)
            ->body(self::AnswerlistAction($request, $tab_id));
    }

    public function AnswerlistAction($request, $tab_id) {
        $pagesize = $request['AND']['per_page'] ? : TopicActivityAnswer::PAGESIZE;
        $es_rs = TopicActivityAnswer::getMatchListForAmdin($tab_id, 1, $pagesize);
        $rs_ids = (array) $es_rs['rows'];
        $rs_total = (int) $es_rs['total'];
        $data = [];
        if($rs_ids && is_array($rs_ids)) {
            $rs = array_values(Photos::getPhotoInfos($rs_ids, 0));
            foreach($rs as $k=>$photo_info) {
                $data[$k]['photo_id'] = $photo_info['id'];
                $data[$k]['remark'] = $photo_info['photo_info']['remark'];
                $data[$k]['image_list'] = $photo_info['photo_info']['image_list'];
                $data[$k]['addtime'] = $photo_info['photo_info']['addtime'];
                $data[$k]['uid'] = $photo_info['user_info']['uid'];
                $data[$k]['nick'] = $photo_info['user_info']['nick'];
            }
        }

        $gridModel = new pGridDataModel($data, $rs_total, [
            'perPage' => $request['per_page'] ? : $request['LIMIT'][1]
        ]);

        $listGrid = Admin::grid($gridModel, function (Grid $grid) {
            $grid->disableFilter();
            $grid->disableExport();
            $grid->disableRowSelector();
            $grid->disableCreateButton();
            $grid->disableActions();
            $grid->column('photo_id', '回答id');
            $grid->column('nick', '作者')->display(function() {
                return "昵称:".$this->nick."<br>uid:".$this->nick;
            });
            $grid->column('remark', '图说')->width(250);
            $grid->column('img_list', '图片')->display(function() {
                $image_rs = '';
                if($this->image_list && is_array($this->image_list)) {
                    foreach($this->image_list as $image) {
                        $image_rs = $image_rs .'<img src="'.$image['pic_url'].'" width="100" />'." ";
                    }
                }
                return $image_rs;
            });
            $grid->column('addtime', '添加时间')->display(function() {
                return date('Y-m-d H:i:s', $this->addtime);
            });

        });

        $list = $listGrid->render();

        return $list;

    }

    public function add(Request $request, Content $content, $id)
    {

        $request = $request->all();
        return $content
            ->header('话题管理')
            ->breadcrumb(
                ['text' => '话题tab管理', 'url' => '/topic/topictab/'.$id],
                ['text' => '添加tab', 'url' => '/topic/topictab/'.$id.'/create']
            )
            ->body(self::editAction($request, $tab_id = 0, $id ));

    }

    public function edit(Request $request, Content $content, $id, $tab_id)
    {

        $request = $request->all();
        return $content
            ->header('话题管理')
            ->breadcrumb(
                ['text' => '话题tab管理', 'url' => '/topic/topictab/'.$id],
                ['text' => '修改tab', 'url' => '/topic/topictab/'.$id.'/'.$tab_id.'/edit']
            )
            ->body(self::editAction($request, $tab_id, $id));


    }

    public function editAction($request, $tab_id, $id)
    {
        $data = [];
        $data['topic_id'] = $id;
        if($tab_id != 0) {
            //修改
            $data = TopicTab::getById($tab_id);
            $data['top_json'] = implode("\r\n", json_decode($data['top_json'], true));
            $search_params = json_decode($data['search_params'], true);
            $data['keyword'] = $search_params['keyword'];
            $data['num'] = $search_params['num'];
            $data['user_profile'] = AdmOperationModule::getPositionRulesById($tab_id, PositionRules::MODULE_TYPE_TOPIC_TAB, true) ?: [];
            if($data['start_time'] == '0000-00-00 00:00:00' && $data['end_time'] == '0000-00-00 00:00:00') {
                $data['show_type'] = self::SHOW_TYPE_NONE;
            } else {
                $data['show_type'] = self::SHOW_TYPE_TIME;
            }
            $form = new Form($data);
            $form->hidden('id');
        } else {
            $data['show_type'] = self::SHOW_TYPE_TIME;
            //添加
            $form = new Form($data);
        }
        $form->hidden('topic_id');
        $form->text('title', 'tab名称')->setWidth(4, 2)->required('不能为空')->help('请输入10字以内');

        $form->radio('show_type', '展示状态')
            ->options([self::SHOW_TYPE_TIME => '时间段展示', self::SHOW_TYPE_NONE => '永不展示'])->checked(self::SHOW_TYPE_TIME)
            ->when(self::SHOW_TYPE_TIME, function(Form $form) {
                $form->datetime('start_time', 'tab开始展示时间');
                $form->datetime('end_time', 'tab结束展示时间')->help('时间段展示时，开始时间和结束时间都为必填项');
            })->when(self::SHOW_TYPE_NONE, function(Form $form) {
                $form->datetime('start_time_hide', 'tab开始展示时间')->readonly();
                $form->datetime('end_time_hide', 'tab结束展示时间')->readonly();
            });

        $form->text('filter_ids', '此tab过滤掉的')->placeholder('id间已英文逗号分隔')->help('非必填项');
        $form->textarea('top_json', '置顶的回答')->placeholder('0025p1m00003wo2l,5 ')->help('非必填项，每行一组:回答id,展现位置(逗号使用英文逗号)');
        $form->divider('已下是气泡信息，可不填');
        $form->fieldset('气泡信息', function (Form $form) {
            $form->imgUpload('pic_id', '气泡图片', false, ['imgType' => ImgUrl::APPTYPE_OP, 'imgSize' => ImgUrl::IMAGE_SIZE_OP_ORI]);
            $form->datetime('pic_start_time', '气泡开始展示时间');
            $form->datetime('pic_end_time', '气泡结束展示时间');
        });
        $form->divider('已上是气泡信息，可不填');
        $form->text('keyword','搜索匹配关键词')->required('必填项')->placeholder('关键词间用英文逗号分隔')->help('请注意：关键词间的关系为并且的关系哦');
        $form->number('num','搜索匹配交互数')->help('非必填项');
        $form->number('tab_sort', 'tab排序')->help('排序值大的tab排在右边');
        $form->userProfile('user_profile', '用户分群')->generate();
        $form->action('/admin/topic/topictab/save');

        return $form->render();
    }

    public function editSubmit(Request $request, Content $content)
    {
        $request = $request->all();
        $data = [];
        $data['topic_id'] = $request['topic_id'];
        $data['title'] = $request['title'];
        $num = (int) $request['num'];
        $data['search_params'] = json_encode(['keyword'=>$request['keyword'],'num'=>$num], JSON_UNESCAPED_UNICODE);
        $data['pic_id'] = $request['pic_id'];
        $data['pic_start_time'] = $request['pic_start_time'];
        $data['pic_end_time'] = $request['pic_end_time'];
        $data['tab_sort'] = $request['tab_sort'];
        $data['top_json'] = json_encode(explode("\n\r", $request['top_json']), JSON_UNESCAPED_UNICODE);
        $data['filter_ids'] = $request['filter_ids'];
        $data['start_time'] = $request['start_time'] ? : '0000-00-00 00:00:00';
        $data['end_time'] = $request['end_time'] ? : '0000-00-00 00:00:00';
        $data['admin_id'] = Admin::user()->id;
        //分群信息
        $userProfile = $request['user_profile'];

        if(mb_strlen($data['title'])>10) {
            throw new InputErrorException('tab名称不能超过10个字哦', InputErrorException::DEFAULT_CODE, 'title');
        }

        if(isset($request['id']) && $request['id']) {
            //修改
            $data['edittime'] = date('Y-m-d H:i:s', time());
            $rs = TopicTab::updateById($request['id'], $data);
        } else {
            //添加
            $data['addtime'] = date('Y-m-d H:i:s', time());
            $rs = TopicTab::add($data);
            $request['id'] = $rs;
        }
        if($rs) {
            //更新用户分群
            AdmOperationModule::addUserProfile($request['id'], $userProfile, PositionRules::MODULE_TYPE_TOPIC_TAB);
            $success = new MessageBag([
                'title' => '提交成功'
            ]);
            return redirect('/admin/topic/topictab/'.$data['topic_id'])->with(compact('success'));
        } else {
            $error = new MessageBag([
                'title' => '提交失败'
            ]);
            return redirect('/admin/topic/topictab/'.$data['topic_id'])->with(compact('error'));
        }


    }

    public function del($topic_id, $tab_id)
    {
        $data = TopicTab::getById($tab_id);
        if($data) {
            $data['is_delete'] = 1;
            $data['edittime'] = date('Y-m-d H:i:s', time());
            $data['admin_id'] = Admin::user()->id;
            $rs = TopicTab::updateById($tab_id, $data);
            if($rs) {
                return response()->json([
                    'status' => true,
                    'message' => "操作成功",
                ]);
            } else {
                return response()->json([
                    'status' => false,
                    'message' => "操作失败",
                ]);
            }
        } else {
            return response()->json([
                'status' => false,
                'message' => "操作失败",
            ]);
        }


    }

    public function sort(Request $request)
    {
        $params = $request->all();
        $sort = $params['sort'];
        if($sort && is_array($sort)) {
            foreach($sort as $sort_key=>$sort_val) {
                $data = [
                    'tab_sort' => $sort_val,
                    'edittime' => date('Y-m-d H:i:s', time()),
                    'admin_id' => Admin::user()->id
                ];
                $id = $sort_key;
                $rs = TopicTab::updateById($id, $data);
            }
        }
        return response()->json([
            'status' => true,
            'message' => "操作成功"
        ]);
    }


}